<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="清单编号" prop="boqCode">
        <el-input
          v-model="queryParams.boqCode"
          placeholder="请输入清单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="清单名称" prop="boqName">
        <el-input
          v-model="queryParams.boqName"
          placeholder="请输入清单名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['project:material:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="材料编号" align="left" prop="boqCode" />
      <el-table-column label="材料名称" align="left" prop="boqName" />
      <el-table-column label="上级材料" align="left" prop="parentCode" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="预付比例" align="center" prop="scale" />
      <el-table-column label="显示排序" align="center" prop="orderNum" />
      <el-table-column label="是否叶节点" align="center" prop="leafNode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.leafNode"/>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['project:material:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.leafNode == 'Y'"
            v-hasPermi="['project:material:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改材料清单对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="材料编号" prop="boqCode">
          <el-input v-model="form.boqCode" placeholder="请输入材料编号" :disabled="updateFlag" />
        </el-form-item>
        <el-form-item label="材料名称" prop="boqName">
          <el-input v-model="form.boqName" placeholder="请输入材料名称" />
        </el-form-item>
        <el-form-item label="上级材料" prop="parentCode">
          <treeselect v-model="form.parentCode" :options="treeOptions" :normalizer="normalizer"
                      placeholder="选择上级清单" noOptionsText="暂无数据" noResultsText="未搜索到匹配项"  :disabled="updateFlag" />
        </el-form-item>
        <el-form-item label="单　　位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="单　　价" prop="price">
          <el-input v-model="form.price" type="number" @keydown.native="handleKey" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="预付比例" prop="scale">
          <el-input-number v-model="form.scale" placeholder="预付比例" :step="10" :min="0" :max="100" style="width: 100%" />
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示排序" />
        </el-form-item>
        <el-form-item label="状　　态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial, exportMaterial, getTreeList, getTreeListExcludeChild } from "@/api/project/material";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Material",
  dicts: ['sys_normal_disable', 'sys_yes_no'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 修改标志
      updateFlag: false,
      // 材料清单表格数据
      materialList: [],
      // 清单树选项
      treeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        boqCode: null,
        boqName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        boqCode: [
          {pattern: /^(\w|-)+$/, message: "材料编号格式不正确", trigger: "blur"},
          { required: true, message: "清单编号不能为空", trigger: "blur" }
        ],
        boqName: [
          { required: true, message: "清单名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询材料清单列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 转换清单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.boqCode,
        label: node.boqName,
        children: node.children
      };
    },
    /** 查询清单下拉树结构 */
    getTreeSelect() {
      getTreeList().then(response => {
        this.treeOptions = this.handleTree(response.data, "boqCode", "parentCode");
      });
    },
    getTreeSelectExcludeChild(row) {
      const id = row.id || this.ids[0];
      getTreeListExcludeChild({id: id}).then(response => {
        this.treeOptions = this.handleTree(response.data, "boqCode", "parentCode");
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        boqId: null,
        boqCode: null,
        boqName: null,
        unit: null,
        price: null,
        scale: null,
        status: "0",
        parentId: null,
        ancestors: null,
        orderNum: null,
        level: null,
        leafNode: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.boqId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeSelect();
      this.updateFlag = false;
      this.open = true;
      this.title = "添加材料清单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const boqId = row.boqId || this.ids
      getMaterial(boqId).then(response => {
        this.form = response.data;
        this.getTreeSelect();
        this.open = true;
        this.updateFlag = true;
        this.title = "修改材料清单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.boqId != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const boqIds = row.boqId || this.ids;
      this.$modal.confirm('确认删除选中的数据项？').then(function() {
        return delMaterial(boqIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('确认导出所有材料清单数据项？').then(() => {
        this.exportLoading = true;
        return exportMaterial(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    handleKey(e) {
      let key = e.key
      // 不允许输入'e'和'.'
      if (key === 'e') {
        e.returnValue = false
        return false
      }
      return true
    }
  }
};
</script>

<style lang="scss">
  input::-webkit-outer-spin-button,
  input::-webkit-inner-spin-button {
    -webkit-appearance: none;
  }
  input[type='number'] {
    -moz-appearance: textfield;
  }
</style>
